package com.hh.us.jetty;

import java.net.URL;
import java.security.ProtectionDomain;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.webapp.WebAppContext;

/**
 * Starter for embedded Jetty. This class is intended to be packaged into a
 * war-file and set as the Main-Class in MANIFEST.MF. Running the war will
 * start a Jetty instance on port 8888 with the containing war loaded.
 * If you specify a port environment variable that will be used for Jetty
 * instead of 8888 (see example).
 * Example:
 * java -jar -Dport=80 -Dapp.context=/ url-shortener.war
 * <p/>
 * url-shortener.war is loaded on http://localhost:8888/
 *
 */
public class JettyStarter {

	private static final int DEFAULT_PORT = 8888;
	private static final String DEFAULT_CONTEXT = "/";

	public static void main(String[] args) throws Exception {
		Server server = new Server();
		int port = Integer.getInteger("port", DEFAULT_PORT);
		String appContext = System.getProperty("app.context", DEFAULT_CONTEXT);
		System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

		HttpConfiguration config = new HttpConfiguration();
		ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(config));
		connector.setReuseAddress(true);
		connector.setIdleTimeout(1000 * 60 * 60);
		connector.setSoLingerTime(-1);
		connector.setPort(port);
		server.setConnectors(new Connector[] { connector });

		WebAppContext context = new WebAppContext();
		context.setServer(server);
		context.setContextPath(appContext);

		ProtectionDomain protectionDomain = JettyStarter.class.getProtectionDomain();
		URL location = protectionDomain.getCodeSource().getLocation();
		context.setWar(location.toExternalForm());

		server.setHandler(context);
		try {
			System.out.println(String.format("Starting web server on port: %s,appContext: %s", port, appContext));
			server.start();
			System.out.println("Starting Complete. Welcome To The URL Shortener :)");
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(100);
		}

	}
}
